﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.Net;
using System.Windows.Forms;
using System.Xml;
using System.Threading;
using System.Diagnostics;
using PlayerTest.Player.Event;

namespace PlayerTest.Player
{
    class VideoHandler
    {
        private int filesize = 0;
        private int playtime = 0;
        private int videoID = -1;
        public int VideoID
        {
            get { return videoID; }
        }

        #region Event Sending
        public event VideoEventHandler EventHandler;
        /// <summary>
        /// Player에게 이벤트 전송
        /// </summary>
        /// <param name="arg"></param>
        private void SendVideoEvent(VideoEventArgs arg)
        {
            // 연결된 모든 함수에 이벤트 전송
            VideoEventHandler handler = EventHandler;
            if (handler != null) handler(this, arg);
        }
        #endregion

        private void SetVideoID()
        {
            if (filesize != 0 && playtime != 0)
            {
                String pageurl = "http://winz.myvnc.com/sub/Controller/video_insert.jsp";
                NameValueCollection myNVC = new NameValueCollection();
                WebClient web_client = new WebClient();

                myNVC.Add("size", Convert.ToString(filesize));
                myNVC.Add("length", Convert.ToString(playtime));
                web_client.QueryString = myNVC;

                Trace.WriteLine(String.Format("미등록 영상입니다. 서버에 영상정보를 등록합니다. filesize : {0} / playtime : {1}", filesize, playtime));

                web_client.UploadValuesCompleted += new UploadValuesCompletedEventHandler(SetVideoID_Completed);
                web_client.UploadValuesAsync(new Uri(pageurl), myNVC);
            }
        }
        /// <summary>
        /// Asynchronous
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SetVideoID_Completed(object sender, UploadValuesCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                String xmlresult = Encoding.UTF8.GetString(e.Result);
                //MessageBox.Show( xmlresult );

                videoID = parseXML(xmlresult);
                Trace.WriteLine(String.Format("  SetVideoID result : {0}", videoID));
            }
            else
            {
                VideoEventArgs arg = new VideoEventArgs(VideoEventArgs.eventtype.ALERT);
                arg.Message= string.Format("서버에 영상정보를 등록하는 도중 오류가 발생하였습니다!\n\n오류 : \n{0}", e.Error.Message);
                SendVideoEvent(arg);
            }
        }

        /// <summary>
        /// 해당 영상의 Video ID를 얻어옵니다.(비동기)
        /// </summary>
        /// <param name="filesize">파일 크기(Byte)</param>
        /// <param name="length">재생 시간(초)</param>
        /// <returns>Video ID</returns>
        public void GetVideoID(int filesize, int playtime)
        {
            if (filesize==0 || playtime==0)
            {
                Trace.WriteLine(
                    string.Format("영상 정보가 잘못되었습니다. FileSize : {0} / PlayTime : {1}", filesize, playtime),
                    "Sub");
            }
            this.playtime = playtime;
            this.filesize = filesize;

            String pageurl = "http://winz.myvnc.com/sub/Controller/video_search.jsp";
            NameValueCollection myNVC = new NameValueCollection();
            WebClient web_client = new WebClient();

            myNVC.Add("size", Convert.ToString(filesize));
            myNVC.Add("length", Convert.ToString(playtime));
            web_client.QueryString = myNVC;

            Trace.WriteLine(String.Format("  영상정보를 검색합니다. filesize : {0} / playtime : {1}", filesize, playtime));

            web_client.UploadValuesCompleted += new UploadValuesCompletedEventHandler(GetVideoID_Completed);
            web_client.UploadValuesAsync(new Uri(pageurl), myNVC);

            /*
            try
            {
                //byte[] res = web_client.UploadValues(new Uri(pageurl), myNVC);
                //int result = parseXML(Encoding.Default.GetString(res));
                //Trace.WriteLine(String.Format(" Query result : {0}", result));
            }
            catch (WebException e)
            {
                MessageBox.Show("서버에서 응답이 없습니다!");
            }
            */
        }

        
        /// <summary>
        /// Asynchronous
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GetVideoID_Completed(object sender, UploadValuesCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                String xmlresult = Encoding.UTF8.GetString(e.Result);
                //MessageBox.Show( xmlresult );

                videoID = parseXML(xmlresult);
                Trace.WriteLine(String.Format("  GetVideoID result : {0}", videoID));
                if (videoID == -1)
                {
                    SetVideoID();
                }
                VideoEventArgs arg = new VideoEventArgs(VideoEventArgs.eventtype.GETVIDEOID);
                SendVideoEvent(arg);
            }
            else
            {
                VideoEventArgs  arg = new VideoEventArgs(VideoEventArgs.eventtype.ALERT);
                arg.Message= string.Format("서버에서 자막 정보를 가져오는 동안 오류가 발생하였습니다!\n\n오류 : \n{0}", e.Error.Message);
                SendVideoEvent( arg );
            }
        }
        

        private int parseXML(String xml)
        {
            int result = 0;
            // XML을 파싱한다.
            XmlDocument xDoc = new XmlDocument();
            xDoc.LoadXml(xml);

            XmlElement rootNode = (XmlElement)xDoc.DocumentElement.FirstChild;
            result = Convert.ToInt32(rootNode.GetAttribute("id"));

            //XmlNodeList children = rootNode.ChildNodes;

            // <item > 순회
            /*
            foreach (XmlElement eNode in children)
            {
                XmlNodeList item_children = eNode.ChildNodes;
                foreach (XmlElement node in item_children)
                {
                    result = Convert.ToInt32(node.GetAttribute("id"));
                }
            }
             */
            return result;
        }
    }
}
